<?php
/**
 * Case Model
 *
 * @property Service $Service
 */
class News extends AdminAppModel
{

    public $useTable = 'news';

/**
 * Display field
 *
 * @var string
 */
    public $displayField = 'title';


/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'news_category_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public $validate = array(
        'name' => array(
            'rule' => 'notEmpty',
        )
    );

    /**
     * 保存新闻信息
     * @param array $requestData 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    public function saveNews($requestData, $isUpdate=false, $news=array() )
    {
        $news = null;
        if ($isUpdate) {
            $news = $news['Admin'];
        }
        $req = $requestData['Admin']['News'];
        // upload title_img
        $titleImg = $this->_uploadTitleImg($req, $isUpdate, $news);
        // upload case_img
        $caseImg = $this->_uploadNewsImg($req, $isUpdate, $news);

        $data = array(
            'News' => array(
                'title' => $req['title'],
                'news_category_id' => $req['news_category_id'],
                'news_memo' => $req['news_memo'],
                'news_desc' => $req['news_desc'],
                'release_date' => $req['release_date'],
                'news_detail_url' => $req['news_detail_url'],
                'news_relation_url' => $req['news_relation_url'],
                'news_icon' => $titleImg,
                'images' => $caseImg,
                'priority' => $req['priority'],
                'updated' => time()
            )
        );
        if ($isUpdate) {
            $this->id = $req['id'];
        } else {
            $this->create();
        }
        if (!$this->save($data)) {
            throw new Exception("The data could not be saved.");
        }
    }
    
    public function getNews($id=null)
    {
        if ($id) {
            $this->id = $id;
            $news = $this->read();

            //$news['News']['features'] = json_decode($news['News']['features'], true);
            $news['News']['images'] = json_decode($news['News']['images'], true);
            $data = array(
                'Admin' => array(
                    'News' => $news['News']
                )
            );
            return $data;
        } 
        return false;
    }

    /**
     * 处理标题的图片logo
     * @param array $requestData 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    private function _uploadTitleImg($requestData, $isUpdate=false, $orginData=array())
    {
        if ($isUpdate) {
            $orginImage = $orginData['News']['news_icon'];
        }
        $uploadFile = $this->upload($requestData['news_icon'], 'title_img_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

    protected function upload($data, $prefix, $exception='upload fail')
    {
        if ($data['size'] == 0) {
            return '';
        }
        if (is_uploaded_file($data['tmp_name'])) {
            $folder = 'uploads/'.date('Ymd');
            if (!is_dir($folder)) {
                mkdir($folder);
            }
            $pathinfo = pathinfo($data['name']);
            $extension = $pathinfo['extension'];
            $filename = uniqid($prefix).'.'.$extension;
            $path = $folder.'/'.$filename;
            if (move_uploaded_file($data['tmp_name'], $path)) {
                return $path;
            }
        }
        throw new Exception($exception);

    }

    /**
     * 处理案例图片的上传
     */
    private function _uploadNewsImg($requestData, $isUpdate)
    {
        if ($isUpdate) {
            $originData = $this->findById($requestData['id']);
            $originImages = json_decode($originData['News']['images'], true);
        }

        $paths = array();
        foreach ($requestData['images'] as $i => $image) {
            if ($isUpdate && $image['size'] == 0) {
                if ($isUpdate) {
                    $paths[$i] = isset($originImages[$i]) ? $originImages[$i] : '';
                } else {
                    $paths[$i] = '';
                }
            } else {
                $paths[$i] = $this->upload($image, 'case_', "upload $i case image fail");
            }
        }
        return json_encode($paths);
    }
}
